<?php
namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Service\DataReturnService as DRS;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;
use App\Common\Base;
use App\Service\CartService;

/**
 * 购物车逻辑
 */
class CartController extends Controller
{

    /**
     * 2018-06-22
     * czw
     * 加入购物车
     * @params id,id  string   以,隔开
     */
    
    public function add(Request $R) 
    {
        $data = $R->post();
        $validator = Validator::make($data,
                [
                    'token' => 'required|string', 
                    'id'    => 'required|array',
                ],
                [
                    'token.required' => 'token不能为空',
                    'id.required'    => '商品id不能为空',
                ]);
        if ($validator->fails()) {
            return DRS::returnError(20003,$validator->errors()->first());
        }

        $userInfo = Base::getUserByToken($data['token']);
        if($userInfo['code'] != '666'){
            return $userInfo;
        }
        $user = $userInfo['data'];

        foreach ($data['id'] as $v){
           $row_product = DB::table('product')->where(['id' => $v, 'business_id' => $user['business_id']])->first();
           $row_cart = DB::table('cart')->where(['user_id' => $user['id'], 'product_id' => $v, 'delete' => 0, 'state' => 0])->first();
           if(!$row_product){
                return DRS::returnError(20285,'商品不存在，无法加入购物车');
           }elseif($row_product->state == 1){
                return DRS::returnError(20285,'商品已禁用，无法加入购物车');
           }elseif($row_product->is_onsale == 0){
                return DRS::returnError(20285,'商品已下架，无法加入购物车');
           }elseif(!in_array($row_product->product_state, [1,2,3,4])){
                return DRS::returnError(20285,'商品已售出，无法加入购物车');
           }elseif($row_cart){
               return DRS::returnError(20008,'商品已入车，无需多次添加');
           }else{
               $cart_insert = [
                    'user_id'       => $user['id'],
                    'product_id'    => $v,
                    'is_own'        => $row_product->is_synchro == 1 ? 0 : 1,
                    'create_time'   => date('Y-m-d H:i:s')
                ];
           }
          $carts_insert[] = $cart_insert;
        }
        if(empty($carts_insert)){
            return DRS::returnError(20007,'商品id有误');
        }
        $row = DB::table('cart')->insert($carts_insert);
        if($row){
            foreach ($data['id'] as $v){
                $row_product = DB::table('product')->where(['id' => $v, 'business_id' => $user['business_id']])->first();
                DB::table('product')->where(['id' => $v, 'business_id' => $user['business_id']])->update(['cart_count'=>$row_product->cart_count+1]);
            }
            return DRS::returnOk(true,'加入购物车成功');
        }else{
            return DRS::returnError(20284,'加入购物车失败');
        }
    }
    
     /**
     * 2018-06-28
     * czw
     * @param id array 多个id以逗号隔开
     * 移除购物车
     */
    public function remove(Request $R)
    {
        $token = $R->get('token');
        $cartIds = $R->get('id');
        $validator = Validator::make(['token' => $token, 'id'=>$cartIds],
                [
                    'token' => 'required|string', 
                    'id'    => 'required',
                ],
                [
                    'token.required' => 'token不能为空',
                    'id.required' => 'id不能为空',
                ]);
        if ($validator->fails()) {
            return DRS::returnError(20003,$validator->errors()->first());
        }
        $userInfo = Base::getUserByToken($token);
        if($userInfo['code'] != '666'){
            return $userInfo;
        }
        $user   = $userInfo['data'];
        
        if(CartService::check_cart($cartIds,$user['id']) == FALSE){
           return DRS::returnError(20280,'购物车不存在该商品');
        }

        $where = [
            ['user_id','=',$user['id']],
            ['delete','=',0], // 没有删除
        ];
        $cart_up = DB::table('cart')->where($where)->whereIn('id',$cartIds)->update(['delete'=>1,'update_time'=>date('Y-m-d H:i:s')]);
        if($cart_up){
            return DRS::returnOk(true,'移除购物车商品成功');
        }else{
            return DRS::returnError(20286,'移除购物车商品失败');
        }
        
    }
    
    /**
     * 2018-06-26
     * czw
     * 购物车列表
     */
    
    public function list(Request $R)
    {
        $token = $R->get('token');
        $validator = Validator::make(['token' => $token],
                [
                    'token' => 'required', 
                ],
                [
                    'token.required' => 'token不能为空',
                ]);
        if ($validator->fails()) {
            return DRS::returnError(20003,$validator->errors()->first());
        }

        $userInfo = Base::getUserByToken($token);
        if($userInfo['code'] != '666'){
            return $userInfo;
        }
        $user = $userInfo['data'];
        $where = [
            'cart.user_id'  => $user['id'],
            'cart.delete'   => 0,
            'cart.state'    => 0,
        ];
        $select = ['cart.id','cart.product_id','cart.state','product.id as product_id','product.pic_url',
                'product.product_name','product.full_name' ,'product.price','product.product_condition','pf.value as product_condition_value',
                'product.systematics_id'];
        $carts = DB::table('cart')
                ->leftJoin('product','cart.product_id','=','product.id')
                ->leftJoin('product_fineness as pf','pf.id', '=', 'product.product_condition')
                ->where($where)
                ->select($select)
                ->get()
                ->toarray();
        
        foreach ($carts as $ckey => $cvalue) {
                $systematics_arr = CartService::set_product_name($cvalue->systematics_id);
                $carts[$ckey]->pre_name = $systematics_arr;
            }
        if($carts){
            return DRS::returnOk($carts,'获取购物车列表成功');
        }else{
            return DRS::returnOk($carts,'购物车没有商品，赶紧去挑选吧');
        }
    }
    
}